<?php

declare(strict_types=1);
/**
 * 小程序统计业务层
 * User：Abell
 * Date：2020/5/25
 */

namespace App\Service;
use App\Constants\ErrorCode;
use App\Dao\WxvisitdDao;
use App\JsonRpc\ServiceConsumer\UserAmountServiceInterface;
use App\Utils\{StringUtil,ServerUtil};
use Psr\Container\ContainerInterface;
use Hyperf\Di\Annotation\Inject;

class WxvisitService
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    private $today_zero;
    public function __construct()
    {
        $this->today_zero = strtotime(date('Y-m-d', time()));
    }

    /** 关键数据趋势API
     * @Author abell
     * @DateTime 2020-06-3
     * @return array
     */
    public function coreData($request){
        // 按日获取微信后台返回的访问人数数据
        $day = array_key_exists('day',$request) ? $request['day'] : 9;
        $request['start_time'] = array_key_exists('start_time',$request) ? $request['start_time'] : strtotime(date('Y-m-d')) - (60 * 60 * 24) * (int)$day;
        $request['end_time'] = array_key_exists('end_time',$request) ? $request['end_time'] : strtotime(date('Y-m-d')) - 1;
        $visit_data = $this->visitHistory($request);
        $visit_data = $visit_data['data']['history'];
        // 生成时间字符串查询充值统计
        $time_list = make(StringUtil::class)->timeArray($request['start_time'],$request['end_time'] + 2,'Ymd',true);
        $client = $this->container->get(UserAmountServiceInterface::class);
        $msg = $client->useRecharge(json_encode(['openid'=>$time_list,'type'=>2]));
        $msg_json = json_decode($msg,true);
        if(!$msg_json['errCode']){
            $msg_array = $msg_json['data'];
            foreach ($visit_data as &$visit_datum) {
                $my_time_formate = strtotime($visit_datum['add_time']);
                $stand_time = date('Ymd',$my_time_formate);
                if(array_key_exists($stand_time,$msg_array)){
                    $visit_datum['amount'] = $msg_array[$stand_time]['amount'];
                    $visit_datum['count'] = $msg_array[$stand_time]['count'];
                    $visit_datum['add_time'] = date('m/d',$my_time_formate);
                }else{
                    $visit_datum['amount'] = $visit_datum['count'] = 0;
                    $visit_datum['add_time'] = date('m/d',$my_time_formate);
                }
            }
        }
        return ['code'=>ErrorCode::SUCCESS, 'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS), 'data'=>$visit_data];
    }

    /** 生成按天统计子页面的访问数据
     * @Author abell
     * @DateTime 2020-05-27
     * @return array
     */
    public function websData($request){
        try {
            $start_time = array_key_exists('start_time',$request) ? $request['start_time'] : strtotime(date('Y-m-d')) - (60 * 60 * 24) * 7;
            $end_time = array_key_exists('end_time',$request) ? $request['end_time'] : time();
            $type_explains = make(WxvisitdDao::class)->webList();
            $type_explains_array = json_decode(json_encode($type_explains),TRUE);
            $type_explains_arr = array_column($type_explains_array,'type_explain');
            // 循环搜索每个子页面的访问数据
            $visit_data = [];
            $visit_num_all = make(WxvisitdDao::class)->visitNum($start_time,$end_time);
            foreach ($type_explains_arr as $type_str) {
                $visit_num = make(WxvisitdDao::class)->webNum($start_time,$end_time,$type_str);
                array_push($visit_data,['type_explain'=>$type_str,
                    'watch'       => $visit_num,
                    'proportion'  => empty($visit_num_all) ? 0 : round($visit_num/$visit_num_all*100)]);
            }
            return ['code'=>ErrorCode::SUCCESS,
                'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),
                'data'=>['data'=>$visit_data,
                    'start_time' => date( "Y-m-d",(int)$start_time),
                    'end_time'    => date( "Y-m-d",(int)$end_time)]];
        }catch (\Exception $e){
            ServerUtil::info('生成按天统计子页面的访问数据/admin/wxvisit/webs',['error'=>$e->getMessage(),'request'=>$request],'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /** 获取基本的访问数据 服务器数据,旧接口
     * @Author abell
     * @DateTime 2020-05-27
     * @return array
     */
    public function visitHistory($request){
        try {
            $start_time = array_key_exists('start_time',$request) ? $request['start_time'] : strtotime(date('Y-m-d')) - (60 * 60 * 24) * 19;
            $end_time = array_key_exists('end_time',$request) ? $request['end_time'] : strtotime(date('Y-m-d')) - 1;
            $today_visit = make(WxvisitdDao::class)->countData(['p_id'=>0],
                ['key'=>'add_time','symbol'=>'>','value'=>$this->today_zero]);
            $today_data = ($end_time > $this->today_zero) ? $today_visit : 0;
            // 判断搜索时间段的数据是否存在,不存在就生成数据
            $left_time = strtotime(date('Y-m-d', (int)$start_time));
            $right_time = strtotime(date('Y-m-d', (int)$end_time));
            parallel([
                // 从左往右执行 每次右边递减
                function() use ($left_time,$right_time){
                    while (($right_time -  $left_time) > 0 ){
                        $right_time -= 86400;
                        make(WxvisitdDao::class)->visitHistory($right_time);
                    }
                    return 'from left to right';
                },
                function() use ($left_time,$right_time){
                    while (($right_time - $left_time) > 0 ){
                        $left_time += 86400;
                        make(WxvisitdDao::class)->visitHistory($left_time);
                    }
                    return 'from right to left';
                }
            ]);
            $weeks_data = make(WxvisitdDao::class)->weekData($start_time,$end_time);
            array_push($weeks_data,['watch'=>$today_data,'add_time'=>date('Y-m-d H:i:s', strtotime(date('Y-m-d', time())))]);
            return ['code'=>ErrorCode::SUCCESS, 'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS), 'data'=>['history'=>$weeks_data, 'today'=>$today_data]];
        }catch (\Exception $e){
            ServerUtil::info('累计访问人数 新版本异步处理/admin/wxvisit/visithistory',['error'=>$e->getMessage(),'request'=>$request],'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /** 获取微信后台数据
     * @Author abell
     * @DateTime 2020-05-27
     * @return array
     */
    public function visitBase($request){
        try {
            $start_time = array_key_exists('start_time',$request) ? date('Ymd',(int)$request['start_time']) : date('Ymd',strtotime('-7 day'));
            $end_time = array_key_exists('end_time',$request) ? date('Ymd',(int)$request['end_time']) : date('Ymd',time());
            $share_pv_all = make(WxvisitdDao::class)->sumData('add_time',$start_time,$end_time,'share_pv');
            $share_uv_all = make(WxvisitdDao::class)->sumData('add_time',$start_time,$end_time,'share_uv');
            $visit_total_all = make(WxvisitdDao::class)->sumData('add_time',$start_time,$end_time,'visit_total');
            $last_share = make(WxvisitdDao::class)->searchData('add_time');
            $last_share['share_pv_all'] = $share_pv_all;
            $last_share['share_uv_all'] = $share_uv_all;
            $last_share['visit_total_all'] = $visit_total_all;
            $pageSize = array_key_exists('pageSize',$request) ? $request['pageSize'] : 15;
            $page_num = array_key_exists('page',$request) ? (int)$request['page'] : 1;
            $daily_retains = make(WxvisitdDao::class)->dayRetain($start_time,$end_time,$pageSize,$page_num);
            return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>[
                'last_record' => $last_share,
                'daily_retain' => $daily_retains
            ]];
        }catch (\Exception $e){
            ServerUtil::info('获取基本的访问数据/admin/wxvisit/visitbase',['error'=>$e->getMessage(),'request'=>$request],'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /** 获取系统后台数据
     * @Author abell
     * @DateTime 2020-05-27
     * @return array
     */
    public function wxDataShow(){
        try {
            $count_all = make(WxvisitdDao::class)->countData(['type_explain' => 'login2reg', 'p_id' => 0]);
            $count_today = make(WxvisitdDao::class)->countData(['type_explain' => 'login2reg', 'p_id' => 0],
                ['key'=>'add_time','symbol'=>'>','value'=>$this->today_zero]);
            return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>['all'=>$count_all,'today'=>$count_today]];
        }catch (\Exception $e){
            ServerUtil::info('显示微信后台数据/admin/wxvisit/wxdata_show',['error'=>$e->getMessage()],'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }
}
